import React from 'react'
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import * as userInfoActionsFrom from '../../actions/userinfo.js'

import Header from '../../components/Header'
import LoginComponent from '../../components/Login'

// import './style.scss'

class Login extends React.Component{
    constructor(props, context){
        super(props, context)
        this.state={
            checking: true
        }
    }
    render() {
        return (
            <div>
                <Header title='登录'></Header>
                {
                    this.state.checking
                    ? <div>正在检查中~~~</div>
                    : <LoginComponent loginHandle={this.loginHandle.bind(this)}></LoginComponent>
                }
            </div>
        )
    }
    componentDidMount() {
        this.doCheck()
    }

    loginHandle(userName) {
        //保存用户名
        const action = this.props.userInfoActions
        let userinfo = this.props.userinfo
        userinfo.userName= userName
        action.update(userinfo)

        //跳转链接
        const router = decodeURIComponent(this.props.match.params.router)
        if(router !== 'undefined') {
            this.props.history.push(router)
        } else{
            this.goUserPage()
        }
    }

    doCheck() {
        const userinfo = this.props.userinfo
        // console.log(userinfo)
        if(userinfo.userName) {
            //已经登录
            this.goUserPage()
        }else{
            //没有登录
            this.setState({
                checking: false
            })
        }
    }

    goUserPage() {
        this.props.history.push('/user')
    }
}



function mapStateToProps(state) {
    return {
        userinfo: state.userinfo
    }
}

function mapDispatchToProps(dispatch) {
    return {
        userInfoActions: bindActionCreators(userInfoActionsFrom, dispatch)
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Login)